#include <vector>
#include <queue>
#include <unordered_set>
using namespace std;

class Solution {
public:
    vector<int> findMinHeightTrees(int n, vector<vector<int>>& edges) {
        if (n == 1) return {0};

        vector<unordered_set<int>> adj(n);
        for (auto& e : edges) {
            adj[e[0]].insert(e[1]);
            adj[e[1]].insert(e[0]);
        }

        queue<int> q;
        for (int i = 0; i < n; ++i) {
            if (adj[i].size() == 1) {
                q.push(i);
            }
        }

        int remaining = n;
        while (remaining > 2) {
            int size = q.size();
            remaining -= size;

            for (int i = 0; i < size; ++i) {
                int leaf = q.front();
                q.pop();

                int neighbor = *adj[leaf].begin();
                adj[neighbor].erase(leaf);

                if (adj[neighbor].size() == 1) {
                    q.push(neighbor);
                }
            }
        }

        vector<int> res;
        while (!q.empty()) {
            res.push_back(q.front());
            q.pop();
        }
        return res;
    }
};